package com.leetcode.tree;

import com.study.common.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @program: leetcode
 * @author: jzhou
 * @date: 2022-11-18 14:45
 * @version: 1.0
 * @description: 二叉树的后序遍历
 **/
public class BinaryTreePostorderTraversal {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();

        // 有一个变量记录上次访问的变量，并且需要中间节点两次进出栈
        TreeNode prev = null;
        while (root != null || !stack.isEmpty()){
            while (root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right == null || root.right == prev){
                list.add(root.val);
                prev = root;
                root = null;
            }else {
                stack.push(root);
                root = root.right;
            }

        }
        return list;
    }
}
